<?php
namespace app\member\controller\api;
use app\ApiController;

use app\channel\model\ProxyUsersModel;
use app\member\model\AccountLogModel;
use app\member\model\AccountModel;
use app\member\model\UsersBindSuperiorModel;
use app\member\model\UsersModel;
use app\member\model\NavMenuModel;
use app\member\model\TeamModel;
use think\Db;
use think\facade\Cache;

/*------------------------------------------------------ */
//-- 会员中心相关API
/*------------------------------------------------------ */

class Center extends ApiController
{
    /*------------------------------------------------------ */
    //-- 优先执行
    /*------------------------------------------------------ */
    public function initialize()
    {
        parent::initialize();
        $this->checkLogin();//验证登陆
        $this->Model = new UsersModel();
    }
    /*------------------------------------------------------ */
    //-- 获取会员中心首页所需数据
    /*------------------------------------------------------ */
    public function getCenterInfo()
    {
        //判断订单模块是否存在
        if(class_exists('app\shop\model\OrderModel')) {
            $OrderModel = new \app\shop\model\OrderModel();
            $data['orderStats'] = $OrderModel->userOrderStats($this->userInfo['user_id']);
            $where = [];
            $where[] = ['user_id','=',$this->userInfo['user_id']];
            $where[] = ['status','=',1];
            $collectNum = (new \app\shop\model\GoodsCollectModel)->where($where)->cache(true, 60)->count('collect_id');
            $data['collectNum'] = $collectNum;
            //$BonusModel = new \app\shop\model\BonusModel();
            //$bonus = $BonusModel->getListByUser();
            //$data['unusedNum'] = $bonus['unusedNum'];//未使用优惠券
        }
        $data['userInfo'] = $this->userInfo;

        $is_channel = (new ProxyUsersModel())->info($this->userInfo['user_id']);

        $data['is_channel'] = $is_channel['proxy_id'] > 0 ? true : false;
        if ($data['is_channel']){
            $channel_proxy_level=Db::name('channel_proxy_level')->where(array('proxy_id'=>$is_channel['proxy_id']))->field('proxy_name')->find();
            $data['userInfo']['role']['name']=$channel_proxy_level['proxy_name'];
            $data['userInfo']['role']['role_name']=$channel_proxy_level['proxy_name'];
        }

        //$data['navMenu'] = (new NavMenuModel)->getRows(3);//我的工具
        $navMenu = (new NavMenuModel)->getRows(3);//我的工具
        foreach ($navMenu as $k => &$menu){
//            if ($this->userInfo['role_id'] <= 0 && $menu['url'] == '/pagesB/channel/order/list?purchase_type=1')
            if ($menu['url'] == '/pagesB/channel/order/list?purchase_type=1' && !$data['is_channel'])
                unset($navMenu[$k]);
            if ($menu['url'] == '/pagesB/channel/center/index' && !$data['is_channel'])
                unset($navMenu[$k]);
            if ($this->userInfo['is_anchor'] != 1 && $menu['url'] == '/pagesA/live/live')
                unset($navMenu[$k]);
        }
        $data['navMenu'] = $navMenu;
        $data['teamCount'] = (new TeamModel)->getTeamCountToCenter($this->userInfo['user_id']);
       //判断是否绑定微信
        $weixin_users_c=Db::name('weixin_users')->where(array('user_id'=>$this->userInfo['user_id']))->count();
        $data['weixin_users_count']=$weixin_users_c;
        return $this->success($data);
    }

    /*------------------------------------------------------ */
    //-- 我的签到
    /*------------------------------------------------------ */
    /*------------------------------------------------------ */
    public function signIndex()
    {
        $year = input('year','','trim');
        $month = input('month','','trim');

        $signInfo = $this->Model->signInfo($this->userInfo['user_id'], $year, $month);
        $signInfo['use_integral'] = $this->Model->signIntegral();
        $signInfo['luckdraw_num'] = $this->Model->signLuckdrawNum();
        $signInfo['timeData'] = ($year && $month) ? strtotime($year . '-' . $month . '-01') : time();
        return $this->success($signInfo);
    }
    /*------------------------------------------------------ */
    //-- 我的签到记录
    /*------------------------------------------------------ */
    /*------------------------------------------------------ */
    public function signLog()
    {
        $yearMonth = input('yearMonth','','trim');
        if (empty($yearMonth)){
            $yearMonth = date('Y-m');
        }
        $signLog = $this->Model->signLog($this->userInfo['user_id'],$yearMonth);
        return $this->success($signLog);
    }
    /*------------------------------------------------------ */
    //-- 签到
    /*------------------------------------------------------ */
    public function signIng()
    {
        $res = $this->Model->signIng($this->userInfo['user_id']);
        if (is_array($res) == false) {
            return $this->error($res);
        }
        return $this->success('签到成功.','',$res);
    }

    public function findJunior()
    {
        $t_user_id = input('user_id');
        $user_id = $this->userInfo['user_id'];
        if($t_user_id == $user_id){
            return $this->error('不能输入自己的ID');
        }
        $UsersBindSuperiorModel = new UsersBindSuperiorModel();
        // 验证下级
        $s_user = $UsersBindSuperiorModel->find($t_user_id);
        if(empty($s_user)){
            return $this->error("无此用户关系链");
        }
        $user = $UsersBindSuperiorModel->find($user_id);
        if(in_array($user_id,explode(',',$s_user['superior'])) == false &&
            in_array($t_user_id,explode(',',$user['superior'])) == false){
            return $this->error("该用户不是同一关系链用户");
        }
        $data = (new UsersModel())->info($t_user_id);
        $data['role_name'] = $data['role']['role_name'];
        $return['list'][] = $data;
        return $this->success($return);
    }

    /*------------------------------------------------------ */
    //-- 转赠
    /*------------------------------------------------------ */
    public function giveBalance()
    {
        $AccountModel = new AccountModel();
        $AccountLogModel = new AccountLogModel();
        $key = "give_use_integral_" . $this->userInfo['user_id'];
        $redis = Cache::get($key);
        if(empty($redis) == false) return $this->error('请勿重复点击');
        Cache::set($key, 1, 30);
        $t_user_id = input('post.user_id');
        $money = input('post.money');
        $user_id = $this->userInfo['user_id'];
        if($money > $this->userInfo['account']['use_integral']){
            Cache::rm($key);
            return $this->error('数额超过余额');
        }
        $give_integral = settings('give_integral');
        if($money > $give_integral){
            Cache::rm($key);
            return $this->error("每日最多赠送{$give_integral}个积分");
        }
        $time = strtotime(date('Y-m-d', time()));
        // 今日已赠送
        $today = $AccountLogModel->where('user_id', $this->userInfo['user_id'])
            ->where('change_type', 20)->where('change_time', '>=', $time)->sum('use_integral') * -1;
        if($today >= $give_integral){
            return $this->error("今日赠送积分已达上限");
        }
        if($today + $money > $give_integral){
            Cache::rm($key);
            return $this->error("每日最多赠送积分{$give_integral}个，当前已赠送{$today}个");
        }
        $UsersBindSuperiorModel = new UsersBindSuperiorModel();
        // 验证关系链
        $t_user = $UsersBindSuperiorModel->find($t_user_id);
        $user = $UsersBindSuperiorModel->find($user_id);
        if(empty($t_user)){
            Cache::rm($key);
            return $this->error("无此用户关系链");
        }
        if(in_array($user_id,explode(',',$t_user['superior'])) == false &&
            in_array($t_user_id,explode(',',$user['superior'])) == false){
            Cache::rm($key);
            return $this->error("该用户不是同一关系链用户");
        }
        // 转账

        Db::startTrans();
        // 扣除
        $data = [
            'change_desc' => '赠与他人',
            'change_type' => 20,
            'use_integral' => $money * -1,
            'by_id' => $t_user_id
        ];
        $set_balance = $AccountModel->change($data,$user_id);
        if($set_balance == false){
            Db::rollback();
            Cache::rm($key);
            return $this->error("转赠失败");
        }
        // 增加
        $data = [
            'change_desc' => '他人赠与',
            'change_type' => 21,
            'use_integral' => $money,
            'by_id' => $user_id
        ];
        $inc_balance = $AccountModel->change($data,$t_user_id);
        if($inc_balance == false){
            Cache::rm($key);
            Db::rollback();
            return $this->error("转赠失败");
        }
        Db::commit();
        Cache::rm($key);
        return $this->success("转赠成功");
    }
}
